<template>
  <div class="todo-mvc">
    <div class="todo-wrapper">
      <TodoTime></TodoTime>
      <!-- 父组件中监听儿子的切换类型事件 -->
      <TodoType :num="todoList.length" @toggle-type="getType"></TodoType>
      <TodoAdd @add="addTodo"></TodoAdd>
      <ul>
        <!--
          监听儿子切换状态的事件
          监听儿子的删除事件
           -->
        <TodoItem
          v-for="item in renderTodoList"
          :key="item.id"
          v-bind="item"
          @updateStatus="updateTodo"
          @del="delTodo"
        ></TodoItem>
        <li v-if="renderTodoList.length === 0">当前类型没有任务，请添加！</li>
      </ul>
    </div>
  </div>
</template>

<script>
import "./index.css";
import TodoTime from "./TodoTime.vue";
import TodoAdd from "./TodoAdd.vue";
import TodoType from "./TodoType.vue";
import TodoItem from "./TodoItem.vue";
export default {
  data() {
    return {
      todoList: [
        {
          id: 1,
          title: "组件",
          isCompleted: false,
        },
        {
          id: 2,
          title: "组件222",
          isCompleted: true,
        },
      ],
      type: "all",
    };
  },
  methods: {
    // 获取儿子需要切换的任务id，然后更新任务的状态
    updateTodo(id) {
      // 找到索引
      let index = this.todoList.findIndex((item) => item.id === id);
      this.todoList[index].isCompleted = !this.todoList[index].isCompleted;
    },
    // 获取儿子删除哪一个，然后执行删除操作
    delTodo(id) {
      let index = this.todoList.findIndex((item) => item.id === id);
      this.todoList.splice(index, 1);
    },
    addTodo(newTodo) {
      let idArr = this.todoList.map((item) => item.id);
      let max = Math.max.apply(null, idArr);
      if(max < 0) max = 0
      let tempObj = {
        id: max + 1,
        title: newTodo,
        isCompleted: false,
      };
      this.todoList.unshift(tempObj);
    },
    // 获取儿子切换的类型
    getType(type) {
      this.type = type;
    },
  },
  computed: {
    // renderTodoList这个计算属性是页面渲染时需要用到的数据，他是根据总的数据数据和任务类型 计算得到的
    renderTodoList() {
      if (this.type === "all") {
        return this.todoList;
      } else if (this.type === "active") {
        return this.todoList.filter((item) => !item.isCompleted);
      } else {
        return this.todoList.filter((item) => item.isCompleted);
      }
    },
  },
  components: {
    TodoTime,
    TodoAdd,
    TodoType,
    TodoItem,
  },
};
</script>

<style>
</style>